'''
Descripttion: 
version: 
Author: jinqian
Date: 2022-05-01 19:38:17
LastEditors: wangjq4214
LastEditTime: 2022-05-01 22:30:54
'''
import jwt
from fastapi import APIRouter, Depends
from fastapi.encoders import jsonable_encoder
from fastapi.responses import JSONResponse
from pydantic import BaseModel

from app.db import get_db
from app.config.config import Config
from app.dao.user import get_user_by_username
from app.utils.errors import UserNotFoundException, PasswordNotMatchException
from app.utils.response import BaseRes


login_router = APIRouter()


class LoginReq(BaseModel):
    username: str
    password: str


class LoginRes(BaseModel):
    token: str


@login_router.post('/login')
async def login(req_body: LoginReq, db=Depends(get_db)):
    user = get_user_by_username(db, req_body.username)
    if user is None:
        raise UserNotFoundException()
    if user.password != req_body.password:
        raise PasswordNotMatchException()

    token = jwt.encode({"id": user.id}, Config.secret, algorithm='HS256')

    return JSONResponse(content=jsonable_encoder(BaseRes(data=LoginRes(token=token))))
